package com.hlg.xboot.web.controller;

import com.hlg.xboot.exceptions.ErrorCode;
import com.hlg.xboot.exceptions.ServerBizException;
import com.hlg.xboot.vo.RestBody;
import com.digi_zones.common.qrcode.QRCodeUtil;
import com.digi_zones.common.utils.RandomValidateCode;
import com.hlg.xboot.service.SMSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.Base64;

/**
 * <p>Description: 公共接口，生成验证码、二维码等</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2017/2/28
 */
@RestController
@RequestMapping("/common")
public class CommonContoller extends BaseController {

    @Autowired
    private SMSService smsService;

    /**
     * 生成二维码，返回二维码图片的base64值
     * @param url 二维码内容
     * @param logoUrl 显示在二维码中间的logo
     * @param size 二维码尺寸，默认256*256
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    public RestBody genQRcode(String url, String logoUrl, Integer size, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        QRCodeUtil.createQrcode(url, logoUrl, baos, size);
        String data = "data:image/jpg;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
        return success(data);
    }

    /**
     * 生成图形验证码，并保存到session中
     * <p>验证码session key参考：com.digi_zones.utils.RandomValidateCode#RANDOM_CODE_KEY</p>
     * @param request
     * @param response
     */
    @RequestMapping(value = "/verifyCode", method = RequestMethod.GET)
    public void genVerifyCode(HttpServletRequest request, HttpServletResponse response){
        RandomValidateCode.genRandcode(request,response);
    }

    /**
     * 发送验证码短信
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/sms/verifyCode", method = RequestMethod.GET)
    public RestBody sendVerifySMS(String phone,Integer type,HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean result = smsService.sendSMS(phone,type);
        if (!result) {
            throw new ServerBizException("短信发送失败", ErrorCode.SERVER_SYSERR);
        }
        return success();
    }

}
